Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Xml
Imports Microsoft.Win32


Public Class Form1
    Public strLogFileIncludingPath As String = String.Empty
    Public strMajorVersion As String = String.Empty
    Public strUserName As String = String.Empty
    Public strPassword As String = String.Empty
    Public strGroupName As String = String.Empty
    Public intMaxNumberThenRestart As Integer = 0
    Public intSEFileOpenedCount As Integer
    Public arrayTCItems As System.Collections.ArrayList
    Public arrayTCRevisions As System.Collections.ArrayList
    Public objSEEC As SolidEdgeFramework.SolidEdgeTCE = Nothing
    Public lngNumberOfFilesToProcess As Long
    Public arrayOfTemplates As Collections.ArrayList
    Public strIXFNames As Collections.ArrayList
    Public intNumberOfLinkedItems As Integer
    Public ArrayItemNumbersToBeProcessed As System.Collections.ArrayList
    Public ArrayItemRevisionsToBeProcessed As System.Collections.ArrayList
    Public arrayListOfLinkedFilesAccordingToSE As Collections.ArrayList
    Public ArrayAlreadyAddedToTextFile As System.Collections.ArrayList
    Public blnBadBom As Boolean = False
    Public strIXFFileNames As System.Collections.ArrayList
    Public strManagedTemplateFolder As String = String.Empty
    Public RevManType As Type
    Public objRevMan As RevisionManager.Application = Nothing
    Public objLinkDocs As RevisionManager.LinkedDocuments = Nothing
    Public objRevManDoc As RevisionManager.Document = Nothing
    Public ListOfLinkedItems As String = Nothing
    Public ListOfLinkedItemRevisions As String = Nothing























    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        ' Get the type from the Solid Edge ProgID
        objSEType = Type.GetTypeFromProgID("SolidEdge.Application")
        ' Get the type from the Revision Manager ProgID
        objRevManType = Type.GetTypeFromProgID("RevisionManager.Application")

        'because of .NET
        OleMessageFilter.Register()

        'check for existence of Log File
        strLogFileIncludingPath = System.IO.Path.GetTempPath + "SEEC_Utilities.log"
        Me.TxtLogFileName.Text = strLogFileIncludingPath

        If oIsValidFileName(strLogFileIncludingPath) Then
            Try
                System.IO.File.Delete(strLogFileIncludingPath)
            Catch ex As Exception
                MessageBox.Show("can not delete " + strLogFileIncludingPath + " " + ex.Message)
            End Try
        End If

        WriteToLogFile(strLogFileIncludingPath, "Started processing at " + Now.ToShortTimeString + " on " + Now.ToShortDateString)

        Dim strSEVersion As String = oGetSolidEdgeVersion()
        Dim nstart As Integer = strSEVersion.IndexOf(".")
        strMajorVersion = strSEVersion.Substring(0, nstart)

        If CInt(strMajorVersion) > 20 Then
            Me.TxtURL.Enabled = True
            ' call sub to pull DB urls from TC
            GetDBUrlsFromXMLFile(oGetSolidEdgePath() + "\TeamcenterDBList.xml")
        End If


    End Sub

    Public Sub GetDBUrlsFromXMLFile(ByVal xmlFileName As String)

        Dim m_xmld As XmlDocument
        Dim m_ComponentsNode As XmlNode = Nothing
        Dim m_ListOfNOdes As XmlNodeList = Nothing
        Dim DBNodes As XmlNodeList = Nothing
        Dim nn As Integer
        Dim m_PropNode As XmlNode = Nothing
        Dim m_SequenceNode As XmlNode = Nothing
        Dim intCtr As Long
        Dim strNodeNAme As String
        Dim strDefaultDB As String = ""
        Dim jj As Integer

        intCtr = 0


        m_xmld = New XmlDocument()
        'Me.LblStatus.Text = "Please wait loading XML file...."
        ' Me.LblStatus.Refresh()
        Try
            m_xmld.Load(xmlFileName)
        Catch ex As Exception
            Exit Sub
        End Try
        Try

            'Me.LblStatus.Text = " "
            'Me.LblStatus.Refresh()

            m_ComponentsNode = m_xmld.SelectSingleNode("/TeamcenterDBList")
            m_ListOfNOdes = m_ComponentsNode.ChildNodes
            For nn = 0 To m_ListOfNOdes.Count - 1
                strNodeNAme = m_ListOfNOdes.Item(nn).Name.ToString
                If strNodeNAme = "DefaultDatabase" Then
                    strDefaultDB = m_ListOfNOdes.Item(nn).InnerText
                ElseIf strNodeNAme = "Databases" Then
                    m_SequenceNode = m_ListOfNOdes.Item(nn)
                    DBNodes = m_ListOfNOdes.Item(nn).SelectNodes("./Database")
                    For jj = 0 To DBNodes.Count - 1
                        m_PropNode = DBNodes.Item(jj)
                        Me.TxtURL.Items.Add(m_PropNode.FirstChild.InnerText)
                    Next

                End If
            Next
            Me.TxtURL.Text = strDefaultDB
        Catch ex As Exception
            MessageBox.Show("error " + ex.Message)
        End Try



        oReleaseObject(m_PropNode)
        oReleaseObject(DBNodes)
        oReleaseObject(m_SequenceNode)
        oReleaseObject(m_ListOfNOdes)
        oReleaseObject(m_ComponentsNode)
        oReleaseObject(m_xmld)
        oForceGarbageCollection()




    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim BadBomCtr As Long
        Dim FileToCheckin As System.Array
        Dim intSEDOCSays As Integer
        Dim strType As String = String.Empty
        Dim strPulledValueForBOMUPDATE As String = String.Empty
        Dim ctr As Long
        Dim strTMP As String = String.Empty
        Dim strFileNameToCheckOut As String = String.Empty
        Dim strFileName As String = String.Empty
        Dim ListOfItemRevIDs As Object = Nothing



        strPulledValueForBOMUPDATE = RegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "BOMUPDATE_INCREMENTAL")



        Me.Label3.Text = ""
        Me.Label3.Refresh()
        Me.Label5.Text = ""
        Me.Label5.Refresh()


        'initialize stuff used
        strUserName = ""
        strPassword = ""
        strGroupName = ""
        intMaxNumberThenRestart = CInt(Me.TxtMaxFiles.Text)
        intSEFileOpenedCount = 0
        BadBomCtr = 0
        intSEDOCSays = 0
        ctr = 1

        strUserName = Me.TxtUserName.Text
        strPassword = Me.TxtPassword.Text
        If Me.TxtGroupName.Text <> "" Then
            strGroupName = Me.TxtGroupName.Text
        End If

        If strUserName = String.Empty Then
            MessageBox.Show("You must enter a username")
            Exit Sub
        End If

        System.Windows.Forms.Cursor.Current = Cursors.WaitCursor

        arrayTCItems = New ArrayList
        arrayTCRevisions = New ArrayList


        If Me.RBCheckForMultipleDataSets.Checked = True Then
            If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                If oConnectToSolidEdge(True, False, "YES") Then
                    intSEFileOpenedCount = 0
                End If
            Else
                oConnectToSolidEdge(True, False)
            End If

            'SE should be started now
            objSEEC = objSEApp.SolidEdgeTCE
            'make sure in TC mode
            objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
            objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


            If Me.RBExcel.Checked = True Then  'read and loop thru each TC item # and revision found in file
                ReadTextFile(Me.TxtExcelName.Text)
                lngNumberOfFilesToProcess = arrayTCItems.Count
            End If

            If Me.RBSpecifySingle.Checked = True Then
                lngNumberOfFilesToProcess = 1
                arrayTCItems.Add(Me.TxtTcItem.Text)
                arrayTCRevisions.Add(Me.TxtTcRev.Text)
            End If

            

            WriteToLogFile(strLogFileIncludingPath, "  ")

            Dim ExtCount As Hashtable = Nothing
            Dim IntCount As Integer = 0

            ExtCount = New Hashtable

            For pp = 0 To arrayTCItems.Count - 1
                ExtCount = New Hashtable
                'Dim intnumberofFiles1 As Integer = 0
                Dim ListOfFilenamesInTC As Object = Nothing
                Dim intnumberofFiles As Integer = 0
                Dim ListOfFilenamesInTC1 As Object = Nothing
                Dim qq As Integer = 0

                Me.Label3.Text = "Checking documents in item revision. " + _
                                        (pp + 1).ToString + " of " + lngNumberOfFilesToProcess.ToString
                Me.Label3.Refresh()
                Try
                    objSEEC.GetListOfFilesFromTeamcenterServer(arrayTCItems.Item(pp), _
                                                      arrayTCRevisions.Item(pp), ListOfFilenamesInTC, intnumberofFiles)
                    For qq = 0 To intnumberofFiles - 1
                        Dim oFname As String = ListOfFilenamesInTC(qq)
                        If oFname = String.Empty Then
                            If ExtCount.ContainsKey("EMPTY") = False Then
                                ExtCount.Add("EMPTY", "1")
                            End If
                            GoTo skipDataset
                        End If
                        Dim strFileExtension As String = oGetFileExtension(oFname)
                        If ExtCount.ContainsKey(strFileExtension.ToLower) = False Then
                            ExtCount.Add(strFileExtension.ToLower, "1")
                        Else
                            Dim oCount As String = ExtCount.Item(strFileExtension.ToLower)
                            IntCount = CInt(oCount)
                            IntCount = IntCount + 1
                            ExtCount.Item(strFileExtension.ToLower) = CStr(IntCount)
                        End If

                        oFname = String.Empty
                        strFileExtension = String.Empty
skipDataset:
                    Next qq

                    If ExtCount.Contains("EMPTY") = True Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " has an EMPTY datset")
                    End If
                    If CInt(ExtCount.Item(".par")) > 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " has more than one SE Part file dataset")
                    End If
                    If CInt(ExtCount.Item(".psm")) > 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " has more than one SE Sheetmetal file dataset")
                    End If
                    If CInt(ExtCount.Item(".pwd")) > 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " has more than one SE Weldment file dataset")
                    End If
                    If CInt(ExtCount.Item(".asm")) > 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " has more than one SE Assembly file dataset")
                    End If
                    If CInt(ExtCount.Item(".jt")) > 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " has more than one JT file dataset")
                    End If
                    If CInt(ExtCount.Item(".par")) >= 1 And CInt(ExtCount.Item(".asm")) >= 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " contains part and assembly dataset")
                    End If
                    If CInt(ExtCount.Item(".par")) >= 1 And CInt(ExtCount.Item(".pwd")) >= 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " contains part and weldment dataset")
                    End If
                    If CInt(ExtCount.Item(".psm")) >= 1 And CInt(ExtCount.Item(".par")) >= 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " contains part and sheetmetal dataset")
                    End If
                    If CInt(ExtCount.Item(".asm")) >= 1 And CInt(ExtCount.Item(".pwd")) >= 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " contains asm and weldment dataset")
                    End If
                    If CInt(ExtCount.Item(".psm")) >= 1 And CInt(ExtCount.Item(".asm")) >= 1 Then
                        WriteToLogFile(strLogFileIncludingPath, arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " contains assy and sheetmetal dataset")
                    End If
                Catch ex As Exception
                    WriteToLogFile(strLogFileIncludingPath, "error getting list of files stored in " + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + "  " + ex.Message)
                End Try              
            Next pp
        End If


        'release stuff
        oReleaseObject(objSEEC)

        'GoTo wrapup



        If Me.RBDownloadOnly.Checked = True Then
            If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                If oConnectToSolidEdge(True, False, "YES") Then
                    intSEFileOpenedCount = 0
                End If
            Else
                oConnectToSolidEdge(True, False)
            End If
            'SE should be started now
            objSEEC = objSEApp.SolidEdgeTCE
            'make sure in TC mode
            objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
            objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)

            If Me.RBExcel.Checked = True Then  'read and loop thru each TC item # and revision found in file
                ReadTextFile(Me.TxtExcelName.Text)
                lngNumberOfFilesToProcess = arrayTCItems.Count
            End If
            If Me.RBSpecifySingle.Checked = True Then
                lngNumberOfFilesToProcess = 1
                arrayTCItems.Add(Me.TxtTcItem.Text)
                arrayTCRevisions.Add(Me.TxtTcRev.Text)
            End If

            WriteToLogFile(strLogFileIncludingPath, "  ")
            objSEEC.GetPDMCachePath(strManagedTemplateFolder)

            strManagedTemplateFolder = Mid(strManagedTemplateFolder, 1, _
                                InStrRev(strManagedTemplateFolder, "\", , CompareMethod.Text))

            arrayOfTemplates = New ArrayList
            strManagedTemplateFolder = strManagedTemplateFolder + "Admin\Solid Edge Templates"

            If System.IO.Directory.Exists(strManagedTemplateFolder) = False Then
                MessageBox.Show("Can not find template folder " + strManagedTemplateFolder, "SEEC Tools", _
                                   MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                Exit Sub
            End If

            FindManagedTemplateDocNumbers(strManagedTemplateFolder)
            WriteToLogFile(strLogFileIncludingPath, "List Of Template IDs are:")
            For kk = 0 To strIXFNames.Count - 1
                strTMP = ReadIXFFIleGetItemNumber(strIXFNames(kk))
                If strTMP <> "" Then
                    arrayOfTemplates.Add(strTMP)
                    WriteToLogFile(strLogFileIncludingPath, strTMP)
                End If
                strTMP = ""
            Next
            WriteToLogFile(strLogFileIncludingPath, "  ")

            For pp = 0 To arrayTCItems.Count - 1
                Dim intnumberofFiles1 As Integer = 0
                Dim ListOfFilenamesInTC As Object = Nothing
                Dim intnumberofFiles As Integer = 0
                Dim ListOfFilenamesInTC1 As Object = Nothing
                If arrayOfTemplates.Contains(arrayTCItems.Item(pp)) = True Then
                    GoTo skippme
                End If
                Me.Label3.Text = "Querying Teamcenter for linked documents. " + _
                        (pp + 1).ToString + " of " + lngNumberOfFilesToProcess.ToString
                Me.Label3.Refresh()
                intNumberOfLinkedItems = -1000

                'export the linked documents out of the TC database
                Me.Label3.Text = "Downloading linked documents to the SEEC cache folder-> " + _
                        pp.ToString + " of " + (lngNumberOfFilesToProcess - 1).ToString
                Me.Label3.Refresh()

                Me.Label5.Text = " "
                Me.Label5.Refresh()


                If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                    If oConnectToSolidEdge(True, False, "YES") Then
                        intSEFileOpenedCount = 0
                    End If
                Else
                    oConnectToSolidEdge(True, False)
                End If
                'SE should be started now
                objSEEC = objSEApp.SolidEdgeTCE
                'make sure in TC mode
                objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


                objSEApp.DisplayAlerts = False
                objSEEC.GetPDMCachePath(strManagedTemplateFolder)
                Try   'get the filenames stored the given item revision
                    objSEEC.GetListOfFilesFromTeamcenterServer(arrayTCItems.Item(pp), _
                            arrayTCRevisions.Item(pp), ListOfFilenamesInTC, intnumberofFiles)

                    If intnumberofFiles = 0 Then
                        'do somthing previous API did not work......
                    Else
                        If Me.CmbFileTypeToProcess.Text <> "All SE File Types" Then
                            If Me.CmbFileTypeToProcess.Text = "SE Parts Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PAR", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Assembly Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".ASM", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Sheetmetal Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PSM", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Draft Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".DFT", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Weldments Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PWD", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            End If
                            intnumberofFiles = 1
                        End If

                        For nn = 0 To intnumberofFiles - 1
                            If strFileNameToCheckOut = "" Then
                                strFileNameToCheckOut = ListOfFilenamesInTC(nn)
                            End If
                            Me.Label5.Text = "Downloading files " + arrayTCItems.Item(pp) + "/" + _
                                arrayTCRevisions.Item(pp) + " with SEEC."

                            Me.Label5.Refresh()


                            Try
                                objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                    arrayTCRevisions.Item(pp), True, strFileNameToCheckOut, _
                                    SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadAllLevel)  'if it is an assembly
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error downloading file " + _
                                    ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                    ArrayItemRevisionsToBeProcessed.Item(pp) + " ->" + ListOfFilenamesInTC(nn) + " " + ex.Message)
                                ' intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skippme
                            End Try

                            strFileName = strManagedTemplateFolder + "\" + strFileNameToCheckOut

                            WriteToLogFile(strLogFileIncludingPath, "Successfully downloaded file " + _
                                arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " ->" + strFileName)
                            strFileName = ""
                            intSEDOCSays = 0
                            intnumberofFiles = 0
                            strFileNameToCheckOut = ""
                        Next nn
                    End If

                Catch ex As Exception
                    WriteToLogFile(strLogFileIncludingPath, "***Error processing file: " + arrayTCItems.Item(pp) + _
                        "/" + arrayTCRevisions.Item(pp) + " " + ex.Message)
                    'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                    GoTo skippme
                End Try
                'End If

                If objSEEC.IsTeamCenterFileCheckedOut(strFileName) = 1 Then    ' 0=checked in 1=checked out
                    Try
                        FileToCheckin = Array.CreateInstance(GetType(Object), 1)
                        FileToCheckin(0) = strFileName
                        objSEEC.CheckInDocumentsToTeamCenterServer(FileToCheckin, False)
                        System.Array.Clear(FileToCheckin, 0, 1)
                    Catch ex As Exception
                        WriteToLogFile(strLogFileIncludingPath, "***Error checking file back into Teamcenter " + strFileName + " " + ex.Message)
                        'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                        GoTo skippme
                    End Try

                End If
skippme:
                intSEFileOpenedCount = intSEFileOpenedCount + 1
            Next pp


        End If



        'release stuff
        oReleaseObject(objSEEC)






        If Me.RBRepairBOM.Checked = True Then  'repair BOM branch
            
            If Me.RBExcel.Checked = True Then  'read and loop thru each TC item # and revision found in file
                ReadTextFile(Me.TxtExcelName.Text)
                lngNumberOfFilesToProcess = arrayTCItems.Count
            End If
            If Me.RBSpecifySingle.Checked = True Then
                lngNumberOfFilesToProcess = 1
                arrayTCItems.Add(Me.TxtTcItem.Text)
                arrayTCRevisions.Add(Me.TxtTcRev.Text)
            End If


            If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                If oConnectToSolidEdge(True, False, "YES") Then
                    intSEFileOpenedCount = 0
                End If
            Else
                oConnectToSolidEdge(True, False)
            End If
            'SE should be started now
            objSEEC = objSEApp.SolidEdgeTCE
            'make sure in TC mode
            objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
            objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


            objSEApp.DisplayAlerts = False


            objSEEC.GetPDMCachePath(strManagedTemplateFolder)
            strManagedTemplateFolder = Mid(strManagedTemplateFolder, 1, _
                   InStrRev(strManagedTemplateFolder, "\", , CompareMethod.Text))
            arrayOfTemplates = New ArrayList
            strManagedTemplateFolder = strManagedTemplateFolder + "Admin\Solid Edge Templates"
            If System.IO.Directory.Exists(strManagedTemplateFolder) = False Then
                MessageBox.Show("Can not find template folder " + strManagedTemplateFolder, "SEEC Tools", _
                                   MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                Exit Sub
            End If

            FindManagedTemplateDocNumbers(strManagedTemplateFolder)
            WriteToLogFile(strLogFileIncludingPath, "List Of Template IDs are:")
            For kk = 0 To strIXFNames.Count - 1
                strTMP = ReadIXFFIleGetItemNumber(strIXFNames(kk))
                If strTMP <> "" Then
                    arrayOfTemplates.Add(strTMP)
                    WriteToLogFile(strLogFileIncludingPath, strTMP)
                End If
                strTMP = ""
            Next

            WriteToLogFile(strLogFileIncludingPath, "  ")

            For pp = 0 To arrayTCItems.Count - 1
                Dim intnumberofFiles1 As Integer = 0
                Dim ListOfFilenamesInTC As Object = Nothing
                Dim intnumberofFiles As Integer = 0
                Dim ListOfFilenamesInTC1 As Object = Nothing
                If arrayOfTemplates.Contains(arrayTCItems.Item(pp)) = True Then
                    WriteToLogFile(strLogFileIncludingPath, "Did not process " + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " because it is a template.")
                    GoTo skipper
                End If
                Me.Label3.Text = "Querying Teamcenter for linked documents. " + _
                        (pp + 1).ToString + " of " + lngNumberOfFilesToProcess.ToString
                Me.Label3.Refresh()

                intNumberOfLinkedItems = -1000

                'export the linked documents out of the TC database
                Me.Label3.Text = "Downloading linked documents to the SEEC cache folder -> " + _
                        pp.ToString + " of " + (lngNumberOfFilesToProcess - 1).ToString
                Me.Label3.Refresh()




                If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                    If oConnectToSolidEdge(True, False, "YES") Then
                        intSEFileOpenedCount = 0
                    End If
                Else
                    oConnectToSolidEdge(True, False)
                End If
                'SE should be started now
                objSEEC = objSEApp.SolidEdgeTCE
                'make sure in TC mode
                objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


                objSEApp.DisplayAlerts = False


                Try

                    objSEApp.DoIdle()
                    objSEApp.DisplayAlerts = False
                    objSEEC.GetPDMCachePath(strManagedTemplateFolder)
                Catch ex As Exception
                    WriteToLogFile(strLogFileIncludingPath, "***Error getting path of SEEC file  " + _
                                  ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                  ArrayItemRevisionsToBeProcessed.Item(pp) + " " + ex.Message)
                    GoTo skipper
                End Try


                Try
                    objSEEC.GetListOfFilesFromTeamcenterServer(arrayTCItems.Item(pp), _
                            arrayTCRevisions.Item(pp), ListOfFilenamesInTC, intnumberofFiles)
                Catch ex As Exception
                    WriteToLogFile(strLogFileIncludingPath, "***Error getting list of file(s) in  " + _
                                  ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                  ArrayItemRevisionsToBeProcessed.Item(pp) + " " + ex.Message)
                    GoTo skipper
                End Try
                Try   'get the filenames stored the given item revision
                    If intnumberofFiles = 0 Then
                        'do somthing previous API did not work......
                    Else
                        If Me.CmbFileTypeToProcess.Text <> "All SE File Types" Then
                            If Me.CmbFileTypeToProcess.Text = "SE Parts Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PAR", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Assembly Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".ASM", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Sheetmetal Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PSM", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Draft Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".DFT", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Weldments Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PWD", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            End If
                            intnumberofFiles = 1
                        End If

                        For nn = 0 To intnumberofFiles - 1
                            If strFileNameToCheckOut = "" Then
                                strFileNameToCheckOut = ListOfFilenamesInTC(nn)
                            End If



                            If oIsSolidEdgeFile(strFileNameToCheckOut) = False Then
                                GoTo skiptoHere1
                            End If


                            
                            Try
                                Me.Label5.Text = "Checking out " + arrayTCItems.Item(pp) + "/" + _
                                                                arrayTCRevisions.Item(pp) + " with SEEC....  please wait."
                                Me.Label5.Refresh()
                                objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                    arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                    SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadFirstLevel)  'if it is an assembly download first level only....  is this necessary
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error downloading file " + _
                                    ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                    ArrayItemRevisionsToBeProcessed.Item(pp) + " ->" + ListOfFilenamesInTC(nn) + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere1
                            End Try

                            strFileName = strManagedTemplateFolder + "\" + strFileNameToCheckOut

                            If strFileName <> "" Then
                                If System.IO.File.Exists(strFileName) = False Then
                                    WriteToLogFile(strLogFileIncludingPath, "***Could not find the assembly in the cache for :" _
                                        + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp))
                                    GoTo skiptoHere1
                                End If
                            End If

                            'need to check in document back into TC
                            Try
                                FileToCheckin = Array.CreateInstance(GetType(Object), 1)
                                FileToCheckin(0) = strFileName
                                objSEEC.CheckInDocumentsToTeamCenterServer(FileToCheckin, False)
                                System.Array.Clear(FileToCheckin, 0, 1)
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error checking file back into Teamcenter " + _
                                    strFileName + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere1
                            End Try

                            Try

                                objSEApp.DoIdle()

                                If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                                    If oConnectToSolidEdge(True, False, "YES") Then
                                        intSEFileOpenedCount = 0
                                    End If
                                Else
                                    oConnectToSolidEdge(True, False)
                                End If
                                If objSEApp Is Nothing Then
                                    WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                                End If

                                objSEEC = objSEApp.SolidEdgeTCE
                                'make sure in TC mode
                                objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)

                                Dim intnumberofFiles2 As Integer = 0
                                Dim ListOfFilenamesInTC2 As Object = Nothing
                                Dim ListOfItemRevIDs1 As Object = Nothing
                                objSEEC.GetBomStructure(arrayTCItems.Item(pp), arrayTCRevisions.Item(pp), _
                                                                Me.CBRevRule.Text, False, intnumberofFiles2, ListOfItemRevIDs1, ListOfFilenamesInTC2)
                               


                            Catch ex As Exception
                                intSEFileOpenedCount = CInt(Me.TxtMaxFiles.Text)

                                Try
                                    If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                                        If oConnectToSolidEdge(True, False, "YES") Then
                                            intSEFileOpenedCount = 0
                                        End If
                                    Else
                                        oConnectToSolidEdge(True, False)
                                    End If


                                    If objSEApp Is Nothing Then
                                        WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                                    End If

                                    objSEEC = objSEApp.SolidEdgeTCE
                                    'make sure in TC mode
                                    objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                                    objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


                                    Dim intnumberofFiles2 As Integer = 0
                                    Dim ListOfFilenamesInTC2 As Object = Nothing
                                    Dim ListOfItemRevIDs1 As Object = Nothing
                                    objSEEC.GetBomStructure(arrayTCItems.Item(pp), arrayTCRevisions.Item(pp), _
                                                                    Me.CBRevRule.Text, False, intnumberofFiles2, ListOfItemRevIDs1, ListOfFilenamesInTC2)



                                Catch ex1 As Exception

                                    WriteToLogFile(strLogFileIncludingPath, "***Error checking number of components in TC BOM " + _
                                        strFileName + " " + ex1.Message)
                                    GoTo skiptoHere1
                                End Try






                            End Try



                            If intnumberofFiles1 = 0 Then   'looks like the BOm is empty    turn incremental update on and do the check-out check-in again
                                Try

                                    'turn ON incremental BOM update
                                    SetRegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "BOMUPDATE_INCREMENTAL", "1")   ' turn incremental ON

                                    Try
                                        Me.Label5.Text = "Checking out " + arrayTCItems.Item(pp) + "/" + _
                                                                        arrayTCRevisions.Item(pp) + " with SEEC....  please wait."
                                        Me.Label5.Refresh()
                                        objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                            arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                            SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadTopLevel)  'if it is an assembly download first level only....  is this necessary
                                    Catch ex As Exception
                                        WriteToLogFile(strLogFileIncludingPath, "***Error downloading file " + _
                                            ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                            ArrayItemRevisionsToBeProcessed.Item(pp) + " ->" + ListOfFilenamesInTC(nn) + " " + ex.Message)
                                        'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                        GoTo skiptoHere1
                                    End Try

                                    strFileName = strManagedTemplateFolder + "\" + strFileNameToCheckOut

                                    If strFileName <> "" Then
                                        If System.IO.File.Exists(strFileName) = False Then
                                            WriteToLogFile(strLogFileIncludingPath, "***Could not find the assembly in the cache for :" _
                                                + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp))
                                            GoTo skiptoHere1
                                        End If
                                    End If

                                    'need to check in document back into TC
                                    Try
                                        FileToCheckin = Array.CreateInstance(GetType(Object), 1)
                                        FileToCheckin(0) = strFileName
                                        objSEEC.CheckInDocumentsToTeamCenterServer(FileToCheckin, False)
                                        System.Array.Clear(FileToCheckin, 0, 1)
                                    Catch ex As Exception
                                        WriteToLogFile(strLogFileIncludingPath, "***Error checking file back into Teamcenter " + _
                                            strFileName + " " + ex.Message)
                                        'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                        GoTo skiptoHere1
                                    End Try


                                    'turn Off incremental BOM update
                                    SetRegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "BOMUPDATE_INCREMENTAL", "0")


                                Catch ex As Exception
                                    'turn Off incremental BOM update
                                    SetRegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "BOMUPDATE_INCREMENTAL", "0")
                                    WriteToLogFile(strLogFileIncludingPath, "***Error re-processing file " + _
                                            strFileName + " " + ex.Message)

                                End Try


                            End If

skiptoHere1:
                            strFileName = ""
                            intSEDOCSays = 0
                            intnumberofFiles = 0
                            strFileNameToCheckOut = ""
                        Next nn
                    End If

                Catch ex As Exception
                    WriteToLogFile(strLogFileIncludingPath, "***Error processing file: " + arrayTCItems.Item(pp) + _
                        "/" + arrayTCRevisions.Item(pp) + " " + ex.Message)
                    'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                    GoTo skipper
                End Try
                'End If

                If objSEEC.IsTeamCenterFileCheckedOut(strFileName) = 1 Then    ' 0=checked in 1=checked out
                    Try
                        FileToCheckin = Array.CreateInstance(GetType(Object), 1)
                        FileToCheckin(0) = strFileName
                        objSEEC.CheckInDocumentsToTeamCenterServer(FileToCheckin, False)
                        System.Array.Clear(FileToCheckin, 0, 1)
                    Catch ex As Exception
                        WriteToLogFile(strLogFileIncludingPath, "***Error checking file back into Teamcenter " + strFileName + " " + ex.Message)
                        'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                        GoTo skipper
                    End Try
                End If
skipper:

                intSEFileOpenedCount = intSEFileOpenedCount + 1

            Next pp
            Me.Label5.Text = " "
            Me.Label5.Refresh()

        End If



        oReleaseObject(objSEEC)






        If Me.RBOpenAndSave.Checked = True Then    'open and save branch!

            arrayListOfLinkedFilesAccordingToSE = New ArrayList
            Try
                'turn ON activate changed part quietly  (the default Setting)
                SetRegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "ACTIVATE_CHANGED_PARTS_QUIETLY", "1")
            Catch ex As Exception

            End Try

            If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                If oConnectToSolidEdge(True, False, "YES") Then
                    intSEFileOpenedCount = 0
                End If
            Else
                oConnectToSolidEdge(True, False)
            End If


            If objSEApp Is Nothing Then
                WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
            End If

            objSEEC = objSEApp.SolidEdgeTCE
            'make sure in TC mode
            objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
            objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


            If Me.RBExcel.Checked = True Then  'read and loop thru each TC item # and revision found in file
                ReadTextFile(Me.TxtExcelName.Text)
                lngNumberOfFilesToProcess = arrayTCItems.Count
            End If

            If Me.RBSpecifySingle.Checked = True Then
                lngNumberOfFilesToProcess = 1
                arrayTCItems.Add(Me.TxtTcItem.Text)
                arrayTCRevisions.Add(Me.TxtTcRev.Text)
            End If
            objSEEC.GetPDMCachePath(strManagedTemplateFolder)
            strManagedTemplateFolder = Mid(strManagedTemplateFolder, 1, _
                    InStrRev(strManagedTemplateFolder, "\", , CompareMethod.Text))

            arrayOfTemplates = New ArrayList
            strManagedTemplateFolder = strManagedTemplateFolder + "Admin\Solid Edge Templates"

            If System.IO.Directory.Exists(strManagedTemplateFolder) = False Then
                MessageBox.Show("Can not find template folder " + strManagedTemplateFolder, "SEEC Tools", _
                                   MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                Exit Sub
            End If

            FindManagedTemplateDocNumbers(strManagedTemplateFolder)
            WriteToLogFile(strLogFileIncludingPath, "List Of Template IDs are:")
            For kk = 0 To strIXFNames.Count - 1
                strTMP = ReadIXFFIleGetItemNumber(strIXFNames(kk))
                If strTMP <> "" Then
                    arrayOfTemplates.Add(strTMP)
                    WriteToLogFile(strLogFileIncludingPath, strTMP)
                End If
                strTMP = ""
            Next

            WriteToLogFile(strLogFileIncludingPath, " ")

            For pp = 0 To arrayTCItems.Count - 1



                Dim intnumberofFiles1 As Integer = 0
                Dim ListOfFilenamesInTC As Object = Nothing
                Dim intnumberofFiles As Integer = 0
                Dim ListOfFilenamesInTC1 As Object = Nothing
                If arrayOfTemplates.Contains(arrayTCItems.Item(pp)) = True Then
                    WriteToLogFile(strLogFileIncludingPath, "Did not process " + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " because it is a template.")
                    GoTo skippy
                End If

                Me.Label3.Text = "Querying Teamcenter for linked documents. " + _
                        (pp + 1).ToString + " of " + lngNumberOfFilesToProcess.ToString
                Me.Label3.Refresh()

                intNumberOfLinkedItems = -1000

                'export the linked documents out of the TC database
                Me.Label3.Text = "Downloading linked documents to the SEEC cache folder -> " + _
                        pp.ToString + " of " + (lngNumberOfFilesToProcess - 1).ToString
                Me.Label3.Refresh()



                If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                    If oConnectToSolidEdge(True, False, "YES") Then
                        intSEFileOpenedCount = 0
                    End If
                Else
                    oConnectToSolidEdge(True, False)
                End If


                If objSEApp Is Nothing Then
                    WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                End If

                objSEEC = objSEApp.SolidEdgeTCE
                'make sure in TC mode
                objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


                objSEApp.DoIdle()
                objSEApp.DisplayAlerts = False
                objSEEC.GetPDMCachePath(strManagedTemplateFolder)
                Try   'get the filenames stored the given item revision
                    objSEEC.GetListOfFilesFromTeamcenterServer(arrayTCItems.Item(pp), _
                            arrayTCRevisions.Item(pp), ListOfFilenamesInTC, intnumberofFiles)
               

                    If intnumberofFiles = 0 Then
                        'do somthing previous API did not work......
                    Else
                        If Me.CmbFileTypeToProcess.Text <> "All SE File Types" Then
                            If Me.CmbFileTypeToProcess.Text = "SE Parts Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PAR", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Assembly Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".ASM", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Sheetmetal Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PSM", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Draft Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".DFT", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            ElseIf Me.CmbFileTypeToProcess.Text = "SE Weldments Only" Then
                                For ii = 0 To intnumberofFiles - 1
                                    If InStr(UCase(ListOfFilenamesInTC(ii)), ".PWD", CompareMethod.Text) <> 0 Then
                                        strFileNameToCheckOut = ListOfFilenamesInTC(ii)
                                    End If
                                Next
                            End If
                            intnumberofFiles = 1
                        End If



                        For nn = 0 To intnumberofFiles - 1
                            If strFileNameToCheckOut = "" Then
                                strFileNameToCheckOut = ListOfFilenamesInTC(nn)
                            End If

                            If oIsSolidEdgeFile(strFileNameToCheckOut) = False Then
                                GoTo skiptoHere
                            End If

                            While intNumberOfLinkedItems = 0

                                If oIsSolidEdgeAssemblylFile(strFileNameToCheckOut) Then
                                    WriteToLogFile(strLogFileIncludingPath, "Empty PSE BOM view : " + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp))
                                End If
                                intNumberOfLinkedItems = intNumberOfLinkedItems + 1
                            End While

                            Try
                                If oIsSolidEdgeAssemblylFile(strFileNameToCheckOut) Then
                                    objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                        arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                        SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadAllLevel)  'if it is an assembly
                                End If

                                If oIsSolidEdgeWeldmentFile(strFileNameToCheckOut) Then
                                    objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                        arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                        SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadAllLevel)  'if it is a weldment
                                End If

                                If oIsSolidEdgePartFile(strFileNameToCheckOut) Then
                                    objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                        arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                        SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadTopLevel)  'if it is a part
                                End If

                                If oIsSolidEdgeSheetMetalFile(strFileNameToCheckOut) Then
                                    objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                        arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                        SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadTopLevel)  'if it is a sheetmetal
                                End If

                                If oIsSolidEdgeDraftFile(strFileNameToCheckOut) Then
                                    objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                        arrayTCRevisions.Item(pp), False, strFileNameToCheckOut, _
                                        SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadTopLevel)  'if it is a draft

                                End If

                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error downloading file " + _
                                    ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                    ArrayItemRevisionsToBeProcessed.Item(pp) + " ->" + ListOfFilenamesInTC(nn) + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere
                            End Try

                            Me.Label5.Text = "Opening the file " + arrayTCItems.Item(pp) + "/" + _
                                arrayTCRevisions.Item(pp) + " with SEEC."

                            Me.Label5.Refresh()

                            strFileName = strManagedTemplateFolder + "\" + strFileNameToCheckOut

                            If System.IO.File.Exists(strFileName) = False Then
                                WriteToLogFile(strLogFileIncludingPath, "***Error downloading file " + _
                                   ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                   ArrayItemRevisionsToBeProcessed.Item(pp) + " ->" + ListOfFilenamesInTC(nn))
                                GoTo skiptoHere
                            End If


                            If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                                If oConnectToSolidEdge(True, False, "YES") Then
                                    intSEFileOpenedCount = 0
                                End If
                            Else
                                oConnectToSolidEdge(True, False)
                            End If


                            If objSEApp Is Nothing Then
                                WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                            End If
                            objSEEC = objSEApp.SolidEdgeTCE
                            'make sure in TC mode
                            objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                            objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


                            Try
                                If objSEEC.IsTeamCenterFileCheckedOut(strFileName) = False Then
                                    WriteToLogFile(strLogFileIncludingPath, ArrayItemNumbersToBeProcessed.Item(pp) + "/" + _
                                   ArrayItemRevisionsToBeProcessed.Item(pp) + " ->" + strFileName)
                                    GoTo skiptoHere
                                End If



                                objSEApp.Documents.Open(strFileName)
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error opening file " + strFileName + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere
                            End Try

                            If Me.CBUpdateDraft.Checked = True Then
                                If objSEApp.ActiveDocumentType = SolidEdgeConstants.DocumentTypeConstants.igDraftDocument Then
                                    Dim objDraftDoc As SolidEdgeDraft.DraftDocument = Nothing
                                    objDraftDoc = objSEApp.ActiveDocument
                                    objDraftDoc.UpdatePropertyTextCacheAndDisplay()
                                    objDraftDoc.UpdatePropertyTextDisplay()
                                    objSEApp.StartCommand(SolidEdgeConstants.DetailCommandConstants.DetailDrawingViewsUpdateViews)
                                End If


                            End If



                            Try
                                objSEApp.ActiveDocument.save()
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error saving file " + strFileName + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere
                            End Try


                            'need to check the just saved document back into TC
                            Try
                                FileToCheckin = Array.CreateInstance(GetType(Object), 1)
                                FileToCheckin(0) = strFileName
                                objSEEC.CheckInDocumentsToTeamCenterServer(FileToCheckin, False)
                                System.Array.Clear(FileToCheckin, 0, 1)
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error checking file back into Teamcenter " + _
                                    strFileName + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere
                            End Try
                            Try
                                objSEApp.ActiveDocument.close()
                            Catch ex As Exception
                                WriteToLogFile(strLogFileIncludingPath, "***Error closing " + strFileName + " " + ex.Message)
                                'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                                GoTo skiptoHere
                            End Try

                            'txtStreamReportStatus.WriteLine("Successfully saved file " + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " ->" + strFileName)

skiptoHere:
                            strFileName = ""
                            intSEDOCSays = 0
                            intnumberofFiles = 0
                            strFileNameToCheckOut = ""
                        Next nn
                    End If

                Catch ex As Exception
                    WriteToLogFile(strLogFileIncludingPath, "***Error processing file: " + arrayTCItems.Item(pp) + _
                        "/" + arrayTCRevisions.Item(pp) + " " + ex.Message)
                    'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                    GoTo skippy
                End Try

                'If oIsValidFileName(strFileName) = False Then
                '    WriteToLogFile(strLogFileIncludingPath, strFileName + " was not checked out! ")
                '    GoTo skippy
                'End If

                'If objSEEC.IsTeamCenterFileCheckedOut(strFileName) = 1 Then    ' 0=checked in 1=checked out
                '    Try
                '        FileToCheckin = Array.CreateInstance(GetType(Object), 1)
                '        FileToCheckin(0) = strFileName
                '        objSEEC.CheckInDocumentsToTeamCenterServer(FileToCheckin, False)
                '        System.Array.Clear(FileToCheckin, 0, 1)
                '    Catch ex As Exception
                '        WriteToLogFile(strLogFileIncludingPath, "***Error checking file back into Teamcenter " + strFileName + " " + ex.Message)
                '        'intSEECCount = CInt(Me.TxtMaxFiles.Text)
                '        GoTo skippy
                '    End Try

                'End If
skippy:

                intSEFileOpenedCount = intSEFileOpenedCount + 1
            Next pp

            Me.Label5.Text = "  "
            Me.Label5.Refresh()

            Me.Label3.Text = "Finished processing. "
            Me.Label3.Refresh()



        End If




        oReleaseObject(objSEEC)






        If Me.RBValidateTCBOM.Checked = True Then

            Dim oFN As String = Me.TxtExcelName.Text
            oFN = Mid(oFN, 1, Len(oFN) - 4)
            oFN = oFN + "_ListWithBadTCBOMs.txt"

            If oIsValidFileName(oFN) Then
                Try
                    System.IO.File.Delete(strLogFileIncludingPath)
                Catch ex As Exception
                    MessageBox.Show("can not delete " + strLogFileIncludingPath + " " + ex.Message)
                End Try
            End If


            arrayListOfLinkedFilesAccordingToSE = New ArrayList
            ArrayAlreadyAddedToTextFile = New ArrayList
            Dim blnCheckForOccurrenceMismatch As Boolean = False

            If Me.CBOccMismatches.Checked = True Then
                blnCheckForOccurrenceMismatch = True
            End If

            strFileNameToCheckOut = ""
            If Me.RBExcel.Checked = True Then  'read and loop thru each TC item # and revision found in file
                ReadTextFile(Me.TxtExcelName.Text)
                lngNumberOfFilesToProcess = arrayTCItems.Count
            End If

            If Me.RBSpecifySingle.Checked = True Then
                lngNumberOfFilesToProcess = 1
                arrayTCItems.Add(Me.TxtTcItem.Text)
                arrayTCRevisions.Add(Me.TxtTcRev.Text)
            End If

            For pp = 0 To lngNumberOfFilesToProcess - 1
                intSEFileOpenedCount = intSEFileOpenedCount + 1

                Dim intnumberofFiles1 As Integer = 0
                Dim ListOfFilenamesInTC As Object = Nothing
                Dim intnumberofFiles As Integer = 0
                Dim ListOfFilenamesInTC1 As Object = Nothing
                Dim ListOfDuplicateObjectIDs As Object = Nothing

                If pp = 0 Then
                    Me.Label3.Text = "Validating 1 of " _
                                       + (2 - 1).ToString + "  ... Please wait."
                    Me.Label3.Refresh()
                Else
                    Me.Label3.Text = "Validating  " + (pp).ToString + " of " _
                                       + (lngNumberOfFilesToProcess - 1).ToString + "  ... Please wait."
                    Me.Label3.Refresh()
                End If


                If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                    If oConnectToSolidEdge(True, False, "YES") Then
                        intSEFileOpenedCount = 0
                    End If
                Else
                    oConnectToSolidEdge(True, False)
                End If


                If objSEApp Is Nothing Then
                    WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                End If

                objSEEC = objSEApp.SolidEdgeTCE
                'make sure in TC mode
                objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)


                objSEEC.GetListOfFilesFromTeamcenterServer(arrayTCItems.Item(pp), _
                    arrayTCRevisions.Item(pp), ListOfFilenamesInTC, intnumberofFiles)
                strFileNameToCheckOut = ""
                If intnumberofFiles > 0 Then
                    For ii = 0 To intnumberofFiles - 1
                        If InStr(UCase(ListOfFilenamesInTC(ii)), ".ASM", CompareMethod.Text) <> 0 Then
                            strFileNameToCheckOut = ListOfFilenamesInTC(ii)  ' this is the one doc in the IR to be checked
                            Exit For
                        End If
                    Next
                End If

                If oIsSolidEdgeAssemblylFile(strFileNameToCheckOut) = False Then
                    GoTo skipover
                End If

                Try
                    objSEEC.CheckBomStructure(arrayTCItems.Item(pp), arrayTCRevisions.Item(pp), Me.CBRevRule.Text, blnBadBom, ListOfDuplicateObjectIDs)
                Catch ex As Exception
                    MsgBox("Error calling API to check TC BOM structure " + ex.Message, MsgBoxStyle.Critical)
                    End
                End Try









                If blnBadBom = True Then
                    BadBomCtr = BadBomCtr + 1
                    WriteToLogFile(oFN, arrayTCItems.Item(pp) + "," + arrayTCRevisions.Item(pp))
                    WriteToLogFile(strLogFileIncludingPath, "***TC BOM contains duplicate BVR lines :" + _
                        arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " filename ->" + strFileNameToCheckOut)
                    If ArrayAlreadyAddedToTextFile.Contains(arrayTCItems.Item(pp) + "," + arrayTCRevisions.Item(pp)) = False Then
                        ArrayAlreadyAddedToTextFile.Add(arrayTCItems.Item(pp) + "," + arrayTCRevisions.Item(pp))
                    End If

                End If



                If blnCheckForOccurrenceMismatch = True Then
                    If strFileNameToCheckOut = "" Then
                        GoTo skipover
                    End If
                    intNumberOfLinkedItems = -1000
                    Try

                        If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                            If oConnectToSolidEdge(True, False, "YES") Then
                                intSEFileOpenedCount = 0
                            End If
                        Else
                            oConnectToSolidEdge(True, False)
                        End If


                        If objSEApp Is Nothing Then
                            WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                        End If


                        If Not (ListOfItemRevIDs Is Nothing) Then
                            ListOfItemRevIDs = Nothing
                        End If
                        objSEEC.GetBomStructure(arrayTCItems.Item(pp), arrayTCRevisions.Item(pp), _
                        Me.CBRevRule.Text, False, intnumberofFiles1, ListOfItemRevIDs, ListOfFilenamesInTC1)
                        intNumberOfLinkedItems = intnumberofFiles1



                        If intNumberOfLinkedItems = 0 Then
                            'log it this is an empty TC BOM
                            BadBomCtr = BadBomCtr + 1
                            WriteToLogFile(strLogFileIncludingPath, " File " + arrayTCItems.Item(pp) + "/" + _
                            arrayTCRevisions.Item(pp) + " contains empty PSE BOM")
                            WriteToLogFile(oFN, arrayTCItems.Item(pp) + "," + arrayTCRevisions.Item(pp))
                        End If
                    Catch ex As Exception
                        'raise error using ITK functions to determined linked TC items
                        WriteToLogFile(strLogFileIncludingPath, "***Error determining if file has PSE BOM: " + _
                            ex.Message + "  " + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + " " + ex.Message)
                        GoTo skipover
                    End Try




                    If intNumberOfLinkedItems >= 0 Then  'download the file and then open with revision manager to see how many occur SE says is there
                        'intSEECCount = intSEECCount + 1

                        If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                            If oConnectToSolidEdge(True, False, "YES") Then
                                intSEFileOpenedCount = 0
                            End If
                        Else
                            oConnectToSolidEdge(True, False)
                        End If


                        If objSEApp Is Nothing Then
                            WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                        End If
                        objSEEC = objSEApp.SolidEdgeTCE
                        'make sure in TC mode
                        objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                        objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)



                        objSEEC.GetPDMCachePath(strManagedTemplateFolder)
                        If Not (ListOfFilenamesInTC Is Nothing) Then
                            ListOfFilenamesInTC = Nothing
                        End If
                        objSEEC.CheckOutDocumentsFromTeamCenterServer(arrayTCItems.Item(pp), _
                                                                arrayTCRevisions.Item(pp), True, strFileNameToCheckOut, SolidEdgeFramework.DocumentDownloadLevel.SEECDownloadTopLevel)
                        strFileName = strManagedTemplateFolder + "\" + strFileNameToCheckOut

                        If strFileName = "" Then
                            strFileName = FindCacheFileCorrespondingToTCItem(arrayTCItems.Item(pp))
                        End If
                        If strFileName <> "" Then
                            If InStr(UCase(strFileName), ".ASM", CompareMethod.Text) = 0 Then
                                WriteToLogFile(strLogFileIncludingPath, "***Could not find the assembly in the cache for :" _
                                    + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp))
                                GoTo skipover
                            End If
                            intSEDOCSays = DetermineNumberOfFirstLevelLinkedDocuments(strFileName)
                            arrayListOfLinkedFilesAccordingToSE.Clear()






                        End If
                        If intSEDOCSays <> intNumberOfLinkedItems Then
                            'check if FOA
                            Dim objPropertySets As SolidEdgeFileProperties.PropertySets = Nothing
                            Dim blnIsFOA As Boolean = False

                            objPropertySets = New SolidEdgeFileProperties.PropertySets
                            objPropertySets.IsFileFamilyOfAssembly(strFileName, blnIsFOA)
                            oReleaseObject(objPropertySets)

                            BadBomCtr = BadBomCtr + 1
                            If ArrayAlreadyAddedToTextFile.Contains(arrayTCItems.Item(pp) + "," + arrayTCRevisions.Item(pp)) = False Then
                                WriteToLogFile(oFN, arrayTCItems.Item(pp) + "," + arrayTCRevisions.Item(pp))
                            End If
                            If blnIsFOA = False Then
                                WriteToLogFile(strLogFileIncludingPath, "***MisMatch in number of occurrences between TC and SE :" + _
                                    arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + ">> PSE says " + _
                                    intNumberOfLinkedItems.ToString + " line items and SE Document says :" + _
                                    intSEDOCSays.ToString)
                            End If

                            If blnIsFOA = True Then
                                WriteToLogFile(strLogFileIncludingPath, "***FOA Assembly potential false positive for MisMatch in number of occurrences between TC and SE :" + _
                                    arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp) + ">> PSE says " + _
                                    intNumberOfLinkedItems.ToString + " line items and SE Document says :" + _
                                    intSEDOCSays.ToString)
                            End If

                        ElseIf intSEDOCSays = intNumberOfLinkedItems Then
                            'txtStreamReportStatus.WriteLine("no problems found with :" + arrayTCItems.Item(pp) + "/" + arrayTCRevisions.Item(pp))
                        End If

                    End If
                End If


skipover:
                strFileName = ""
                intSEDOCSays = 0
                intnumberofFiles = 0
                strFileNameToCheckOut = ""
                intNumberOfLinkedItems = 0
                blnBadBom = False

            Next
            WriteToLogFile(strLogFileIncludingPath, "  ")
            WriteToLogFile(strLogFileIncludingPath, "Found total of " + BadBomCtr.ToString + " BOM mismatches.")

            ArrayAlreadyAddedToTextFile.Clear()

        End If


        If Me.RBFindFilesBasedOnType.Checked = True Then

            Me.Label3.Text = "Searching Teamcenter database for ALL file of the specified Solid Edge file type"
            Me.Label3.Refresh()

            If Me.RBSheetmetal.Checked = True Then
                strType = "SE SheetMetal"
            End If
            If Me.RBAssemblies.Checked = True Then
                strType = "SE Assembly"
            End If
            If Me.RBDrafts.Checked = True Then
                strType = "SE Draft"
            End If
            If Me.RBParts.Checked = True Then
                strType = "SE Part"
            End If
            If Me.RBWeldments.Checked = True Then
                strType = "SE Weldment"
            End If

            Try
                intNumberOfLinkedItems = 0
                ListOfLinkedItems = ""
                ListOfLinkedItemRevisions = ""

               
                If intSEFileOpenedCount >= intMaxNumberThenRestart Then
                    If oConnectToSolidEdge(True, False, "YES") Then
                        intSEFileOpenedCount = 0
                    End If
                Else
                    oConnectToSolidEdge(True, False)
                End If


                If objSEApp Is Nothing Then
                    WriteToLogFile(strLogFileIncludingPath, "***Error could not connect to Solid Edge ")
                End If

                objSEEC = objSEApp.SolidEdgeTCE
                'make sure in TC mode
                objSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, True)
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)

                objSEEC = objSEApp.SolidEdgeTCE

                'If Not (ListOfItemRevIDs Is Nothing) Then
                '    ListOfItemRevIDs.clear()
                'End If

                If strType = "SE Draft" Then
                    objSEEC.GetItemRevBasedOnSEType(SolidEdgeFramework.TCESETypes.TCE_SEDraft, "*", ListOfItemRevIDs)
                ElseIf strType = "SE Weldment" Then
                    objSEEC.GetItemRevBasedOnSEType(SolidEdgeFramework.TCESETypes.TCE_SEWeldment, "*", ListOfItemRevIDs)
                ElseIf strType = "SE Assembly" Then
                    objSEEC.GetItemRevBasedOnSEType(SolidEdgeFramework.TCESETypes.TCE_SEAssembly, "*", ListOfItemRevIDs)
                ElseIf strType = "SE Part" Then
                    objSEEC.GetItemRevBasedOnSEType(SolidEdgeFramework.TCESETypes.TCE_SEPart, "*", _
                        ListOfItemRevIDs)
                ElseIf strType = "SE SheetMetal" Then
                    objSEEC.GetItemRevBasedOnSEType(SolidEdgeFramework.TCESETypes.TCE_SESheetmetal, "*", ListOfItemRevIDs)
                End If

                'read into text file

               


                Try
                    For ii = 0 To ListOfItemRevIDs.length / 2 - 1
                        WriteToLogFile(Me.TxtFileWithListOfFilesFound.Text, ListOfItemRevIDs(ii, 0) + "," + ListOfItemRevIDs(ii, 1))
                    Next
                    intNumberOfLinkedItems = CLng(ListOfItemRevIDs.length) / 2
                Catch ex As Exception

                End Try

             







                Me.Label3.Text = "Found " + intNumberOfLinkedItems.ToString + _
                    " files.  See text file containing the list of files."
                Me.Label3.Refresh()
                Me.Button5.Enabled = True
                'MessageBox.Show("Found " + intNumberOfLinkedItems.ToString + " Files", "test", MessageBoxButtons.OK, MessageBoxIcon.Information)


            Catch ex As Exception
                'Beep()
            End Try



        End If













wrapup:
        WriteToLogFile(strLogFileIncludingPath, "  ")
        WriteToLogFile(strLogFileIncludingPath, "Finished processing " + Now.Date.ToShortDateString + "   " + Now.ToLongTimeString)

        System.Windows.Forms.Cursor.Current = Cursors.Default

        Try
            Do While objSEApp.Documents.Count <> 0
                objSEApp.ActiveDocument.close()
            Loop
            objSEApp.Quit()
            oReleaseObject(objSEEC)
            oReleaseObject(objSEApp)

        Catch ex As Exception
            oKillProcess("Edge.exe")
            oKillProcess("iCnct.exe")
        End Try



        'turn ON incremental BOM update  (the default Setting)
        SetRegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "BOMUPDATE_INCREMENTAL", "1")

        'turn OFF activate changed part quietly  (the default Setting)
        SetRegValue(RegistryHive.CurrentUser, "Software\Unigraphics Solutions\Solid Edge\Version " + strMajorVersion + "\DEBUG", "ACTIVATE_CHANGED_PARTS_QUIETLY", "0")

        Me.Button4.Enabled = True


        Me.Label3.Text = "Finished processing."
        Me.Label3.Refresh()


    End Sub

    Public Function RegValue(ByVal Hive As RegistryHive, ByVal Key As String, ByVal ValueName As String) As String
        Dim objParent As RegistryKey = Nothing
        Dim objSubkey As RegistryKey = Nothing
        Dim sAns As String = Nothing
        Dim ErrInfo As String = Nothing
        Select Case Hive
            Case RegistryHive.ClassesRoot
                objParent = Registry.ClassesRoot
            Case RegistryHive.CurrentConfig
                objParent = Registry.CurrentConfig
            Case RegistryHive.CurrentUser
                objParent = Registry.CurrentUser
            Case RegistryHive.LocalMachine
                objParent = Registry.LocalMachine
            Case RegistryHive.PerformanceData
                objParent = Registry.PerformanceData
            Case RegistryHive.Users
                objParent = Registry.Users
        End Select
        Try
            objSubkey = objParent.OpenSubKey(Key)
            'if can't be found, object is not initialized
            If Not objSubkey Is Nothing Then
                sAns = (objSubkey.GetValue(ValueName))
                RegValue = (objSubkey.GetValue(ValueName))
                objSubkey.Close()
            End If
        Catch ex As Exception
            ErrInfo = ex.Message
        Finally
            If ErrInfo = "" And sAns = "" Then
                ErrInfo = _
                   "No value found for requested registry key"
                RegValue = "No value found for requested registry key"
            End If
        End Try
        Return sAns
    End Function

 
    Private Sub RBExcel_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBExcel.CheckedChanged
        If RBExcel.Checked = True Then
            Me.Button3.Enabled = True
            Me.TxtExcelName.Enabled = True
        Else
            Me.Button3.Enabled = False
            Me.TxtExcelName.Enabled = False
        End If
    End Sub

    Private Sub RBSpecifySingle_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBSpecifySingle.CheckedChanged
        If Me.RBSpecifySingle.Checked = True Then
            Me.TxtTcRev.Enabled = True
            Me.TxtTcItem.Enabled = True
        End If

        If Me.RBSpecifySingle.Checked = False Then
            Me.TxtTcRev.Enabled = False
            Me.TxtTcItem.Enabled = False
        End If
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        With OpenFileDialog1
            .Filter = "Text Files (*.txt) | *.txt"
            .ShowDialog()
        End With
        Me.TxtExcelName.Text = OpenFileDialog1.FileName

        OpenFileDialog1.Dispose()
    End Sub

    Public Function SetRegValue(ByVal Hive As RegistryHive, ByVal Key As String, ByVal ValueName As String, ByVal intValue As Integer) As String


        Dim objParent As RegistryKey = Nothing
        Dim objSubkey As RegistryKey = Nothing
        Dim sAns As String = ""
        Dim ErrInfo As String = ""

        Select Case Hive
            Case RegistryHive.ClassesRoot
                objParent = Registry.ClassesRoot
            Case RegistryHive.CurrentConfig
                objParent = Registry.CurrentConfig
            Case RegistryHive.CurrentUser
                objParent = Registry.CurrentUser
            Case RegistryHive.LocalMachine
                objParent = Registry.LocalMachine
            Case RegistryHive.PerformanceData
                objParent = Registry.PerformanceData
            Case RegistryHive.Users
                objParent = Registry.Users

        End Select

        Try
            objSubkey = objParent.OpenSubKey(Key, True)
            'if can't be found, object is not initialized
            If Not objSubkey Is Nothing Then
                sAns = (objSubkey.GetValue(ValueName))
                objSubkey.SetValue(ValueName, CInt(intValue))
                objSubkey.Close()
            End If

        Catch ex As Exception

            ErrInfo = ex.Message
        Finally

            'if no error but value is empty, populate errinfo
            If ErrInfo = "" And sAns = "" Then
                ErrInfo = _
                   "No value found for requested registry key"

                SetRegValue = "No value found for requested registry key"
            End If
        End Try
        Return sAns
    End Function

    Public Sub FindManagedTemplateDocNumbers(ByVal oPath As String)
        strIXFNames = New ArrayList
        ReadFileNamesFromDirectory(oPath, True, "*.ixf", strIXFNames)

    End Sub

    ' Recursively travels through a directory structure saving all files into an array.
    Public Sub ReadFileNamesFromDirectory(ByVal sourceDir As String, ByVal fRecursive As Boolean, ByVal filter As String, ByVal strIXFFileNames As ArrayList)
        Dim sDir As String

        Dim sDirInfo As IO.DirectoryInfo
        Dim sFile As String
        Dim sFileInfo As IO.FileInfo

        Dim count As Integer
        ' Add trailing separators to the supplied paths if they don't exist. 
        If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
            sourceDir &= System.IO.Path.DirectorySeparatorChar
        End If

        ' Recursive switch to continue drilling down into directory structure. 
        If fRecursive Then
            ' Get a list of directories from the current parent. 
            For Each sDir In System.IO.Directory.GetDirectories(sourceDir)
                sDirInfo = New System.IO.DirectoryInfo(sDir)
                ' Since we are in recursive mode
                ReadFileNamesFromDirectory(sDirInfo.FullName, fRecursive, filter, strIXFFileNames)
                sDirInfo = Nothing

            Next
        End If

        count = System.IO.Directory.GetFiles(sourceDir, filter).Length
        'ReDim Preserve strFileNames(intFileNameCount + count)
        ' Get the files from the current parent. 
        For Each sFile In System.IO.Directory.GetFiles(sourceDir, filter)
            sFileInfo = New System.IO.FileInfo(sFile)

            'strFileNames(intFileNameCount) = sFileInfo.FullName
            strIXFFileNames.Add(sFileInfo.FullName)
            'Me.ListBox1.Items.Add(sFileInfo.FullName)
            sFileInfo = Nothing
        Next
        count = 0
    End Sub

    Public Function ReadIXFFIleGetItemNumber(ByVal IXFFileName As String) As String

        Dim m_xmld As XmlDocument
        Dim m_ComponentsNode As XmlNode = Nothing
        Dim tempID As String
        m_xmld = New XmlDocument()
        ReadIXFFIleGetItemNumber = ""
        Try
            m_xmld.Load(IXFFileName)
        Catch ex As Exception
            ReadIXFFIleGetItemNumber = ""
            Exit Function
        End Try
        Try
            m_ComponentsNode = m_xmld.SelectSingleNode("/ixfInfo/FileInfo/ImanInfo/ItemID")
            ReadIXFFIleGetItemNumber = m_ComponentsNode.InnerText

            If Not (m_ComponentsNode Is Nothing) Then
                m_ComponentsNode = Nothing
            End If
            If Not (m_xmld Is Nothing) Then
                m_xmld = Nothing
            End If
            Exit Function

        Catch ex As Exception
            ReadIXFFIleGetItemNumber = ""
        End Try


skipIXF:
        If Not (m_ComponentsNode Is Nothing) Then
            m_ComponentsNode = Nothing
        End If
        If Not (m_xmld Is Nothing) Then
            m_xmld = Nothing
        End If
        ReadIXFFIleGetItemNumber = ""

    End Function

    Public Function FindCacheFileCorrespondingToTCItem(ByVal strTCItemNumber As String) As String
        Dim jj As Long

        strIXFFileNames = New ArrayList
        'get a COMPLETE list of IXF files found in the TC connection folder
        ReadFileNamesFromDirectory(strManagedTemplateFolder, False, "*.ixf", strIXFFileNames)

        For jj = 0 To strIXFFileNames.Count - 1

            FindCacheFileCorrespondingToTCItem = ReadIXFFIle(strIXFFileNames.Item(jj), strTCItemNumber)
            If FindCacheFileCorrespondingToTCItem <> "" Then
                Exit Function
            End If
        Next


        FindCacheFileCorrespondingToTCItem = ""
    End Function

    Public Function DetermineNumberOfFirstLevelLinkedDocuments(ByVal oFilename) As Integer

        Dim nn As Integer
        Dim ctr As Integer
        ctr = 0
        nn = 1
        Dim junk As String



        Try

            If objRevMan Is Nothing Then
                objRevMan = Activator.CreateInstance(RevManType)
                objRevMan.Visible = False
                objRevMan.DisplayAlerts = False
                objRevMan.ResolveLink = False
            End If
        Catch ex As Exception

            Try
                ObjRevMan = CreateObject("RevisionManager.Application")
                ObjRevMan.Visible = False
                ObjRevMan.DisplayAlerts = False
                ObjRevMan.ResolveLink = False
            Catch ex1 As Exception
                DetermineNumberOfFirstLevelLinkedDocuments = -1
                oReleaseObject(objLinkDocs)
                oReleaseObject(objRevManDoc)
                oReleaseObject(objRevMan)
                Exit Function
            End Try
        End Try



        Try

            If System.IO.File.Exists(oFilename) = False Then  ' can not find the file in the SEEC cache
                DetermineNumberOfFirstLevelLinkedDocuments = -100
                oReleaseObject(objLinkDocs)
                oReleaseObject(objRevManDoc)
                'Garbage_Collect(ObjRevMan)
                Exit Function
            End If

            objRevManDoc = ObjRevMan.Open(oFilename)


        Catch ex As Exception
            'could not open the file for some reason...  kil and try it again

            Try
                ObjRevMan.Quit()
                oReleaseObject(objLinkDocs)
                oReleaseObject(objRevManDoc)
                oReleaseObject(objRevMan)
            Catch ex2 As Exception

            End Try



            Try

                ObjRevMan = CreateObject("RevisionManager.Application")
                ObjRevMan.Visible = False
                ObjRevMan.DisplayAlerts = False
                ObjRevMan.ResolveLink = False
                objRevManDoc = ObjRevMan.Open(oFilename)
                GoTo skipToOverHere
            Catch ex1 As Exception
                DetermineNumberOfFirstLevelLinkedDocuments = -200
                oReleaseObject(objLinkDocs)
                oReleaseObject(objRevManDoc)
                oReleaseObject(objRevMan)
                Exit Function
            End Try


            DetermineNumberOfFirstLevelLinkedDocuments = -2
            oReleaseObject(objLinkDocs)
            oReleaseObject(objRevManDoc)
            oReleaseObject(objRevMan)
            Exit Function
        End Try

skipToOverHere:

        Try
            objLinkDocs = objRevManDoc.LinkedDocuments(RevisionManager.LinkTypeConstants.seLinkTypeNormal)
        Catch ex As Exception
            DetermineNumberOfFirstLevelLinkedDocuments = -3
            oReleaseObject(objLinkDocs)
            oReleaseObject(objRevManDoc)
            oReleaseObject(objRevMan)
            Exit Function
        End Try


        Try


            'DetermineNumberOfFirstLevelLinkedDocuments = objLinkDocs.Count

            For nn = 1 To objLinkDocs.Count
                'objLinkDocs.Item(nn).occurrences()
                Dim strLinkedFileName As String = objLinkDocs.Item(nn).fullname
                strLinkedFileName = System.IO.Path.GetFileName(strLinkedFileName)

                If arrayListOfLinkedFilesAccordingToSE.Contains(strLinkedFileName.ToUpper) = False Then
                    arrayListOfLinkedFilesAccordingToSE.Add(strLinkedFileName.ToUpper)
                End If
                ctr = ctr + objLinkDocs.Item(nn).occurrences()
            Next
            DetermineNumberOfFirstLevelLinkedDocuments = ctr
            'ObjRevMan.Quit()

            oReleaseObject(objLinkDocs)
            oReleaseObject(objRevManDoc)

            'If Not (ObjRevMan Is Nothing) Then     ***** leave revision manager running
            '    Marshal.ReleaseComObject(ObjRevMan)
            '    ObjRevMan = Nothing
            'End If

            oForceGarbageCollection()

            Exit Function

        Catch ex As System.Exception
            'MsgBox("Error opening assembly in Revision Manager " + fname, MsgBoxStyle.OKOnly)
            DetermineNumberOfFirstLevelLinkedDocuments = -1000
            oReleaseObject(objLinkDocs)
            oReleaseObject(objRevManDoc)
            oReleaseObject(objRevMan)
            Exit Function
        End Try




    End Function



    Public Function ReadIXFFIle(ByVal IXFFileName As String, ByVal ItemNo As String) As String

        Dim m_xmld As XmlDocument
        Dim m_ComponentsNode As XmlNode = Nothing
        Dim tempID As String
        m_xmld = New XmlDocument()
        ReadIXFFIle = ""
        Try
            m_xmld.Load(IXFFileName)
        Catch ex As Exception
            ReadIXFFIle = ""
            Exit Function
        End Try
        Try
            m_ComponentsNode = m_xmld.SelectSingleNode("/ixfInfo/FileInfo/ImanInfo/ItemID")
            tempID = m_ComponentsNode.InnerText
            If tempID = ItemNo Then
                m_ComponentsNode = m_xmld.SelectSingleNode("/ixfInfo/FileInfo/FileSpec")
                ReadIXFFIle = m_ComponentsNode.InnerText




                If Not (m_ComponentsNode Is Nothing) Then
                    m_ComponentsNode = Nothing
                End If
                If Not (m_xmld Is Nothing) Then
                    m_xmld = Nothing
                End If
                Exit Function
            End If
        Catch ex As Exception
            ReadIXFFIle = ""
        End Try


skipIXF:
        If Not (m_ComponentsNode Is Nothing) Then
            m_ComponentsNode = Nothing
        End If
        If Not (m_xmld Is Nothing) Then
            m_xmld = Nothing
        End If
        ReadIXFFIle = ""

    End Function


    Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
        Dim FSO4 As Scripting.FileSystemObject = Nothing
        Dim strPathToNotpad As String


        Try

            FSO4 = New Scripting.FileSystemObject
            strPathToNotpad = FSO4.GetSpecialFolder(Scripting.SpecialFolderConst.WindowsFolder).Path + "\notepad.exe"

            Call Shell(strPathToNotpad + " " + Me.TxtFileWithListOfFilesFound.Text, AppWinStyle.NormalFocus)
        Catch ex As Exception
            MsgBox("Error displaying file", MsgBoxStyle.OkOnly)
        End Try


        If Not (FSO4 Is Nothing) Then
            FSO4 = Nothing
        End If

        oForceGarbageCollection()
    End Sub

    Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
        Dim FSO2 As Scripting.FileSystemObject = Nothing
        Dim strPathToNotpad As String

        Try

            FSO2 = New Scripting.FileSystemObject
            strPathToNotpad = FSO2.GetSpecialFolder(Scripting.SpecialFolderConst.WindowsFolder).Path + "\notepad.exe"

            Call Shell(strPathToNotpad + " " + Me.TxtLogFileName.Text, AppWinStyle.NormalFocus)
        Catch ex As Exception
            MsgBox("Error displaying file", MsgBoxStyle.OkOnly)
        End Try


        If Not (FSO2 Is Nothing) Then
            FSO2 = Nothing
        End If


        oForceGarbageCollection()
    End Sub

    Private Sub RBFindFilesBasedOnType_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBFindFilesBasedOnType.CheckedChanged

        If Me.RBFindFilesBasedOnType.Checked = True Then
            Me.GBDocTypes.Enabled = True
            Me.GroupBox1.Enabled = False

            Me.Label3.Text = "Generate a list of Item IDs and Revisions by querying the Teamcenter database."
            Me.Label3.Refresh()
            Me.Label5.Text = "You must select the Solid Edge file type."
            Me.Label5.Refresh()


        Else
            Me.GBDocTypes.Enabled = False
            Me.TxtFileWithListOfFilesFound.Text = ""
        End If
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        End

    End Sub

    Private Sub RBAssemblies_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBAssemblies.CheckedChanged
        Dim FSO As Scripting.FileSystemObject = Nothing
        Dim strTypeOfFile As String
        strTypeOfFile = ""
        Me.TxtFileWithListOfFilesFound.Text = ""
        ' add code to name text file to place the results in
        If Me.RBParts.Checked = True Then
            strTypeOfFile = "ListOfParts-"
        End If
        If Me.RBSheetmetal.Checked = True Then
            strTypeOfFile = "ListOfSheetMetal-"
        End If
        If Me.RBAssemblies.Checked = True Then
            strTypeOfFile = "ListOfAssemblies-"
        End If
        If Me.RBDrafts.Checked = True Then
            strTypeOfFile = "ListOfDrafts-"
        End If
        If Me.RBWeldments.Checked = True Then
            strTypeOfFile = "ListOfWeldments-"
        End If
        Try
            If (FSO Is Nothing) Then
                FSO = New Scripting.FileSystemObject
            End If
            Me.TxtFileWithListOfFilesFound.Text = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder).Path + "\" + strTypeOfFile + Now.Minute.ToString + Now.Second.ToString + ".txt"
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RBParts_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBParts.CheckedChanged
        Dim FSO As Scripting.FileSystemObject = Nothing
        Dim strTypeOfFile As String
        strTypeOfFile = ""
        Me.TxtFileWithListOfFilesFound.Text = ""
        ' add code to name text file to place the results in
        If Me.RBParts.Checked = True Then
            strTypeOfFile = "ListOfParts-"
        End If
        If Me.RBSheetmetal.Checked = True Then
            strTypeOfFile = "ListOfSheetMetal-"
        End If
        If Me.RBAssemblies.Checked = True Then
            strTypeOfFile = "ListOfAssemblies-"
        End If
        If Me.RBDrafts.Checked = True Then
            strTypeOfFile = "ListOfDrafts-"
        End If
        If Me.RBWeldments.Checked = True Then
            strTypeOfFile = "ListOfWeldments-"
        End If
        Try
            If (FSO Is Nothing) Then
                FSO = New Scripting.FileSystemObject
            End If
            Me.TxtFileWithListOfFilesFound.Text = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder).Path + "\" + strTypeOfFile + Now.Minute.ToString + Now.Second.ToString + ".txt"
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RBSheetmetal_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBSheetmetal.CheckedChanged
        Dim FSO As Scripting.FileSystemObject = Nothing
        Dim strTypeOfFile As String
        strTypeOfFile = ""
        Me.TxtFileWithListOfFilesFound.Text = ""
        ' add code to name text file to place the results in
        If Me.RBParts.Checked = True Then
            strTypeOfFile = "ListOfParts-"
        End If
        If Me.RBSheetmetal.Checked = True Then
            strTypeOfFile = "ListOfSheetMetal-"
        End If
        If Me.RBAssemblies.Checked = True Then
            strTypeOfFile = "ListOfAssemblies-"
        End If
        If Me.RBDrafts.Checked = True Then
            strTypeOfFile = "ListOfDrafts-"
        End If
        If Me.RBWeldments.Checked = True Then
            strTypeOfFile = "ListOfWeldments-"
        End If
        Try
            If (FSO Is Nothing) Then
                FSO = New Scripting.FileSystemObject
            End If
            Me.TxtFileWithListOfFilesFound.Text = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder).Path + "\" + strTypeOfFile + Now.Minute.ToString + Now.Second.ToString + ".txt"
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RBDrafts_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBDrafts.CheckedChanged
        Dim FSO As Scripting.FileSystemObject = Nothing
        Dim strTypeOfFile As String
        strTypeOfFile = ""
        Me.TxtFileWithListOfFilesFound.Text = ""
        ' add code to name text file to place the results in
        If Me.RBParts.Checked = True Then
            strTypeOfFile = "ListOfParts-"
        End If
        If Me.RBSheetmetal.Checked = True Then
            strTypeOfFile = "ListOfSheetMetal-"
        End If
        If Me.RBAssemblies.Checked = True Then
            strTypeOfFile = "ListOfAssemblies-"
        End If
        If Me.RBDrafts.Checked = True Then
            strTypeOfFile = "ListOfDrafts-"
        End If
        If Me.RBWeldments.Checked = True Then
            strTypeOfFile = "ListOfWeldments-"
        End If
        Try
            If (FSO Is Nothing) Then
                FSO = New Scripting.FileSystemObject
            End If
            Me.TxtFileWithListOfFilesFound.Text = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder).Path + "\" + strTypeOfFile + Now.Minute.ToString + Now.Second.ToString + ".txt"
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RBWeldments_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBWeldments.CheckedChanged
        Dim FSO As Scripting.FileSystemObject = Nothing
        Dim strTypeOfFile As String
        strTypeOfFile = ""
        Me.TxtFileWithListOfFilesFound.Text = ""
        ' add code to name text file to place the results in
        If Me.RBParts.Checked = True Then
            strTypeOfFile = "ListOfParts-"
        End If
        If Me.RBSheetmetal.Checked = True Then
            strTypeOfFile = "ListOfSheetMetal-"
        End If
        If Me.RBAssemblies.Checked = True Then
            strTypeOfFile = "ListOfAssemblies-"
        End If
        If Me.RBDrafts.Checked = True Then
            strTypeOfFile = "ListOfDrafts-"
        End If
        If Me.RBWeldments.Checked = True Then
            strTypeOfFile = "ListOfWeldments-"
        End If
        Try
            If (FSO Is Nothing) Then
                FSO = New Scripting.FileSystemObject
            End If
            Me.TxtFileWithListOfFilesFound.Text = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder).Path + "\" + strTypeOfFile + Now.Minute.ToString + Now.Second.ToString + ".txt"
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RBValidateTCBOM_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RBValidateTCBOM.CheckedChanged
        If RBValidateTCBOM.Checked = True Then

            Me.GroupBox1.Enabled = True
            Me.Label3.Text = "Perform a BOM comparison to identify Solid Edge assemblies when the TC BOM view contains duplicate BOM lines."
            Me.Label3.Refresh()
            Me.Label5.Text = ""
            Me.Label5.Refresh()
            Me.CBOccMismatches.Enabled = True
        End If
        If RBValidateTCBOM.Checked = False Then

            Me.CBOccMismatches.Enabled = False
        End If

        If Me.RBValidateTCBOM.Checked = True Then
            Me.TxtMaxFiles.Text = 500
        End If
    End Sub
End Class
